import QtQuick 1.1
import com.nokia.meego 1.0
//import com.nokia.extras 1.0
import "Logic.js" as Logic

Page {
    id: pageWordsList

    property string selWordId: ""
    property string selWordCategoryId: ""
    property string selWord: ""
    property string selWordTransl: ""
    property bool isEditWord: false

    tools: ToolBarLayout {
        id: tool_only_back
        opacity: userTheme.opacityToolbar
        ToolIcon {
            id: toolIconBack
            //iconId: "toolbar-back"
            iconSource: "images/toolbar/back.png"
            onClicked: {
                pageStack.pop();
            }
        }
        ToolIcon {
            id: toolIconRemove
            //iconId: "toolbar-delete"
            iconSource: "images/toolbar/close.png"
            onClicked: {
                if( selWordId != "" ) {
                    dlgRemoveWord.open()
                }
            }
        }
        ToolIcon {
            id: toolIconEdit
            //iconId: "toolbar-edit"
            iconSource: "images/toolbar/edit.png"
            onClicked: {
                isEditWord = true
                Logic.openFile("AddWords.qml")
            }
        }
        ToolIcon {
            id: toolIconAdd
            //iconId: "toolbar-add"
            iconSource: "images/toolbar/add.png"
            onClicked: {
                isEditWord = false
                Logic.openFile("AddWords.qml")
            }
        }
        ToolIcon {
            id: toolIconOpt
            //iconId: "toolbar-view-menu"
            iconSource: "images/toolbar/properties.png"
            onClicked: menuListWords.status == DialogStatus.Closed ? menuListWords.open() : menuListWords.close()
        }
    } //ToolBarLayout

    Menu {
        id: menuListWords
        visualParent: pageStack
        MenuLayout {
            MenuItem {
                text: qsTr("Reset filter");
                visible: appWindow.filterWords.length > 0
                onClicked: { resetFilterWords() }
            }
            MenuItem { text: qsTr("Filter by categories"); onClicked: { dlgFilterWords.open() } }
            MenuItem { text: qsTr("Search"); onClicked: { dlgSearch.open() } }
        }
    }

    /*-----------------------------------------------------------------------------*/

    QNMTitle {
        id: titlePage
        text: appWindow.filterWords.length > 0 ? qsTr("List of words (f)") : qsTr("List of words")
        image: "images/words.png"
        busy: false
    }

    BackgroundPage { }

    function getAllWords() {
        titlePage.busy = true

        /*----------*/
        var bufCategoriesFilter = appWindow.filterWords
        if( bufCategoriesFilter .length > 0 ) {
            getAllWordsByCategories()
            titlePage.busy = false
            return
        }

        /*----------*/

        //console.log("getAllWords()")
        var db = Logic.getDatabase()

        listModelWords.clear()

        db.transaction( function(tx) {
                           var res = tx.executeSql ( "SELECT words.*, c.id AS category_id, c.category AS category FROM words LEFT JOIN categories AS c ON words.category_id == c.id" )
                           for( var i = 0; i<=res.rows.length-1; i++ ) {
                               if ( i == 0 ) {
                                   selWordId = res.rows.item(i).id;
                                   selWord = res.rows.item(i).word;
                                   selWordTransl = res.rows.item(i).translation;
                                   selWordCategoryId = res.rows.item(i).category_id;
                               }
                               var id = res.rows.item(i).id;
                               var nameWord = res.rows.item(i).word;
                               var transWord = res.rows.item(i).translation;
                               var nameCategory = res.rows.item(i).category;
                               var idCategory = res.rows.item(i).category_id;
                               listModelWords.append( {word_id: id, word: nameWord, translation: transWord, category: nameCategory, category_id: idCategory } );
                           }
                       }
                    )
        /* установка значение для первого элемента */
        titlePage.busy = false
    }

    function removeWord( _id ) {
        var db = Logic.getDatabase()
        db.transaction( function(tx) {
                           console.log( "DELETE FROM words WHERE id=" + _id  )
                           var res = tx.executeSql( "DELETE FROM words WHERE id=?",_id )
                           console.log("Delete: "+res)
                       }
                )

        //переинициализация списка категорий
        getAllWords()
    }

    /*------------------------------------------------------*/

    ListModel {
        id: listModelWords
        Component.onCompleted: getAllWords()
    }


    ScrollDecorator { flickableItem: listViewWords }
    ListView {
        id: listViewWords

        anchors.top: titlePage.bottom
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        anchors.leftMargin: 4
        anchors.rightMargin: 4
        anchors.bottomMargin: 5
        anchors.topMargin: 5

        // Компонент отображения пункта
        Component {
            id: compItemListWord
            //Item {
            Image {
                id: wrapper
                source: "images/wordItem.png"
                smooth: true
                height: 120
                width: listViewWords.width
                scale: 0.95
                opacity: 0.75

                Rectangle {
                    id: wrapper1
                    anchors.centerIn: parent
                    height: parent.height - 10
                    width: parent.width - 30
                    color: "transparent"
                    clip: true
                    Item {
                        id: wordSrc
                        anchors.top: parent.top
                        anchors.topMargin: 2
                        anchors.left: parent.left
                        anchors.leftMargin: 25
                        height: parent.height/3
                        width: parent.width - 40
                        clip: true
                        Text {
                            anchors.verticalCenter: parent.verticalCenter
                            color: userTheme.colorWord
                            text: cppMeeWords.remEnter(word)
                            font.pixelSize: 28
                            smooth: true
                            font.family: "Nokia Pure Text"
                        }
                    }

                    Item {
                        id: wordTransl
                        anchors.top: wordSrc.bottom
                        anchors.left: parent.left
                        anchors.leftMargin: 25
                        height: parent.height/3
                        width: parent.width - 40
                        clip: true
                        Text {
                            anchors.verticalCenter: parent.verticalCenter
                            color: userTheme.colorTranslation
                            text: cppMeeWords.remEnter(translation)
                            font.pixelSize: 28
                            smooth: true
                            font.family: "Nokia Pure Text"
                        }
                    }

                    Item {
                        id: wordsCategory
                        anchors.top: wordTransl.bottom
                        anchors.left: parent.left
                        anchors.leftMargin: 25
                        height: parent.height/3
                        width: parent.width - 40
                        clip: true
                        Text {
                            anchors.verticalCenter: parent.verticalCenter
                            color: userTheme.colorCategory
                            text: qsTr("Category") + ": " + cppMeeWords.remEnter(category)
                            font.pixelSize: 24
                            smooth: true
                            font.family: "Nokia Pure Text"
                        }
                    }
                }

                states: State {
                    name: "Current"
                    when: wrapper.ListView.isCurrentItem
                    PropertyChanges { target: wrapper; scale: 1.0 }
                    PropertyChanges { target: wrapper; opacity: 1.0 }
                }

                transitions: Transition {
                    NumberAnimation { properties: "scale"; duration: 300 }
                    NumberAnimation { properties: "opacity"; duration: 300 }
                }

                MouseArea {
                    id: mouseAreaItem;
                    anchors.fill: parent

                    onClicked: {
                        wrapper.ListView.view.currentIndex = index
                        selWordId = word_id
                        selWord = word
                        selWordTransl = translation
                        selWordCategoryId = category_id
                    }

                    onDoubleClicked: {
                        parent.ListView.view.currentIndex = index
                        isEditWord = true
                        selWordId = word_id
                        selWord = word
                        selWordTransl = translation
                        selWordCategoryId = category_id
                        Logic.openFile("AddWords.qml")
                    }
                }
            }
        }

        //компонент подсветки пункта меню
        Component {
            id: sessionItemHighlight
            Rectangle {
                height: 100
                width: listViewWords.width
                radius: 12
                y: listViewWords.currentItem.y;
                Behavior on y { SpringAnimation { spring: 5; damping: 0.3 } }
                gradient: Gradient {
                    GradientStop { position: 0; color: "#8997ff" }
                    GradientStop { position: 0.5; color: "lightsteelblue" }
                    GradientStop { position: 1; color: "#8997ff" }
                }
            }
        }


        model: listModelWords
        delegate: compItemListWord
        //highlight: sessionItemHighlight
        highlightFollowsCurrentItem: true
        focus: true
        clip: true
    }

    /*QueryDialog {
        id: dlgRemoveCategory
        icon: "image://theme/icon-m-toolbar-delete-white"
        titleText: qsTr("Deleting word")
        message: qsTr("Delete selected word ?")
        acceptButtonText: qsTr("Yes")
        rejectButtonText: qsTr("No")
        onAccepted: removeWord( selWordId )
    }*/


    QueryDialog {
        id: dlgRemoveWord
        icon: "image://theme/icon-m-toolbar-delete-white"
        titleText: qsTr("Deleting word")
        message: qsTr("Delete selected word ?")
        acceptButtonText: qsTr("Yes")
        rejectButtonText: qsTr("No")
        onAccepted: removeWord( selWordId )
    }

    /********************************************************************/
    function getAllCategories() {
        var db = Logic.getDatabase()

        listModelCategories.clear()
        menuListWords.enabled = false

        db.transaction( function(tx) {
                           var res = tx.executeSql( "SELECT id,category FROM categories" )
                           for(var i = 0; i<=res.rows.length-1; i++) {
                               menuListWords.enabled = true
                               var _id = res.rows.item(i).id;
                               var nameCategory = res.rows.item(i).category;
                               //var descrCategory = res.rows.item(i).description;
                               listModelCategories.append( { name: nameCategory, category_id: _id } );
                           }
                       }
                    )
        /* установка значение для первого элемента */
        //titlePage.busy = false
    }

    /* ********************************************************************* */
    function getAllWordsByCategories ( ) {
        /* считываем индексы выбранных категорий */
        var bufCategoriesFilter = appWindow.filterWords

        var db = Logic.getDatabase()
        listModelWords.clear()
        db.transaction ( function(tx) {
                           var sql = "SELECT words.*, c.category FROM words LEFT JOIN categories AS c ON words.category_id == c.id "
                           for(var s=0; s<bufCategoriesFilter.length; s++) {
                               if ( s == 0 ) {
                                   sql += " WHERE  category_id = " + bufCategoriesFilter[s]
                               } else {
                                   sql += " OR category_id = " + bufCategoriesFilter[s]
                               }
                           }
                           console.log(sql)
                           var res = tx.executeSql( sql )
                           for ( var i = 0; i<=res.rows.length-1; i++ ) {
                               if ( i == 0 ) {
                                   selWordId = res.rows.item(i).id;
                                   selWord = res.rows.item(i).word;
                                   selWordTransl = res.rows.item(i).translation;
                                   selWordCategoryId = res.rows.item(i).category_id;
                               }
                               var id = res.rows.item(i).id;
                               var nameWord = res.rows.item(i).word;
                               var transWord = res.rows.item(i).translation;
                               var nameCategory = res.rows.item(i).category;
                               var idCategory = res.rows.item(i).category_id;
                               listModelWords.append( {word_id: id, word: nameWord, translation: transWord, category: nameCategory, category_id: idCategory } );
                           }
                       }
                    )
    }

    /*************************************************/

    ListModel {
        id: listModelSelectedCategories
    }

    ListModel {
        id: listModelCategories
        Component.onCompleted: {
            getAllCategories()
        }
    }

    MultiSelectionDialog {
        id: dlgFilterWords
        titleText: qsTr("Selected categories")
        model: listModelCategories
        acceptButtonText: qsTr("Accept filter")
        rejectButtonText: qsTr("Reset filter")
        selectedIndexes: appWindow.filterWords_indx

        onAccepted: {
            appWindow.filterWords_indx = dlgFilterWords.selectedIndexes

            var lSel = selectedIndexes.length
            var bufCategoriesFilter = new Array()
            listModelSelectedCategories.clear()
            for ( var j=0; j<lSel; j++ ) {
                listModelSelectedCategories.append( { name: dlgFilterWords.model.get( dlgFilterWords.selectedIndexes[j] ).name } );
                var category_id = dlgFilterWords.model.get( dlgFilterWords.selectedIndexes[j] ).category_id
                bufCategoriesFilter[ bufCategoriesFilter.length ] = category_id
                console.log( bufCategoriesFilter[ bufCategoriesFilter.length-1 ] )
            }
            appWindow.filterWords = bufCategoriesFilter

            getAllWordsByCategories()
        }

        onRejected: {
            resetFilterWords()
        }
    }
    /*************************************************/
    function resetFilterWords () {
        var bufCategoriesFilter = new Array()
        appWindow.filterWords = bufCategoriesFilter
        appWindow.filterWords_indx = []
        dlgFilterWords.selectedIndexes = []
        getAllWords()
    }

    /*************************************************/
    Dialog {
        id: dlgSearch
        title: Item {
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.verticalCenter: parent.verticalCenter
            height: 140
            Image {
                anchors.centerIn: parent
                source: "image://theme/icon-l-search"
            }
        }

        content: Item {
            id: contentItem
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.verticalCenter: parent.verticalCenter
            width: parent.width
            height: 100
            TextField {
                id: textSearch
                width: parent.width
                height: 50
            }
        }
        buttons: Button {
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.verticalCenter: parent.verticalCenter
            width: parent.width*0.8;
            height: 80;
            text: qsTr("Search");
            platformStyle: ButtonStyle{ inverted: true }
            onClicked: {
                getAllWordsBySearch( textSearch.text )
                dlgSearch.close()
            }
        }
    }

    function getAllWordsBySearch ( strSearch ) {
        if( strSearch === "" ) {
            getAllWords()
            return
        }

        titlePage.busy = true
        var db = Logic.getDatabase()

        listModelWords.clear()

        db.transaction( function(tx) {
                           var res = tx.executeSql ( "SELECT words.*, c.id AS category_id, c.category AS category FROM words "+
                                                    " LEFT JOIN categories AS c ON words.category_id == c.id " +
                                                    "WHERE words.word LIKE '%" +strSearch+"%' OR words.translation LIKE '%" + strSearch + "%' "  )
                           for( var i = 0; i<=res.rows.length-1; i++ ) {
                               if ( i == 0 ) {
                                   selWordId = res.rows.item(i).id;
                                   selWord = res.rows.item(i).word;
                                   selWordTransl = res.rows.item(i).translation;
                                   selWordCategoryId = res.rows.item(i).category_id;
                               }
                               var id = res.rows.item(i).id;
                               var nameWord = res.rows.item(i).word;
                               var transWord = res.rows.item(i).translation;
                               var nameCategory = res.rows.item(i).category;
                               var idCategory = res.rows.item(i).category_id;
                               listModelWords.append( {word_id: id, word: nameWord, translation: transWord, category: nameCategory, category_id: idCategory } );
                           }
                       }
                    )
        /* установка значение для первого элемента */
        titlePage.busy = false
    }
}
